﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Umbrella.Whs.SharePoint;

namespace Umbrella.Whs.WhsAddin.ConsoleControls
{
    public partial class Connecting : ConsoleControlBase
    {
        private InstallationManager.InstallationStatus _status;

        public Connecting(UmbrellaConsoleTab tab)
            : base(tab)
        {
            if (_log.IsDebugEnabled)
                _log.Debug("Initialization start");

            try
            {
                InitializeComponent();

                // done
                if (_log.IsDebugEnabled)
                    _log.Debug("Initialization done");
            }
            catch (Exception e)
            {
                _log.Fatal("Failed to initialize", e);

                throw;
            }
        }

        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var im = new InstallationManager();

                _status = im.GetInstallationStatus();
            }
            catch (Exception x)
            {
                _log.Error("Failed determine SharePoint installation status", x);
            }
        }

        private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                // determine status
                switch (_status)
                {
                    case InstallationManager.InstallationStatus.NotInstalled:
                        AddinStateManager.Instance.SetState(AddinState.SharePointNotInstalled);
                        break;

                    case InstallationManager.InstallationStatus.NotUmbrella:
                        AddinStateManager.Instance.SetState(AddinState.SharePointNotUmbrella);
                        break;

                    default:
                        // force debug?
                        AddinStateManager.Instance.SetState(
                            Properties.Settings.Default.DebugForceSharePointNotUmbrellaMode ?
                            AddinState.SharePointNotUmbrella :
                            AddinState.Ready
                            );
                        break;
                }
            }
            catch (Exception x)
            {
                _log.Error("Failed to handle devices-found status", x);

                throw;
            }
        }

        private void Connecting_Load(object sender, EventArgs e)
        {
            _status = InstallationManager.InstallationStatus.NotInstalled;

            this.bgWorker.RunWorkerAsync();
        }
    }
}
